#include "DiskUtils.h"

DiskUtils::DiskUtils() {}

DiskUtils::~DiskUtils() {}

void DiskUtils::readFromDisk(char* buffer, int offset, int size) {
	int fd = open("FILE_SYS", O_RDONLY, 0666);
	if (pread(fd,buffer,size,offset) == -1) {
		cout << strerror(errno) << endl;
	}
	close(fd);
}

int DiskUtils::readFromDisk(unsigned char* buffer, int offset, int size) {
	int fd = open("FILE_SYS", O_RDONLY, 0666);
	int bytesRead = pread(fd,buffer,size,offset);
	if (bytesRead == -1) {
		cout << strerror(errno) << endl;
	}
	close(fd);
	return bytesRead;
}

void DiskUtils::readFromDisk(int* buffer, int offset, int size) {
	int fd = open("FILE_SYS", O_RDONLY, 0666);
	if (pread(fd,buffer,size,offset) == -1) {
		cout << strerror(errno) << endl;
	}
	close(fd);
}

void DiskUtils::writeToDisk(int* buffer, int offset ,int size) {
	int fd = open("FILE_SYS", O_WRONLY, 0666);
	if (pwrite(fd,buffer,size,offset) == -1) {
		cout << strerror(errno) << endl;
	}
	close(fd);
}

int DiskUtils::writeToDisk(unsigned char* buffer, int offset ,int size) {
	int fd = open("FILE_SYS", O_WRONLY, 0666);
	int bytesWriten = pwrite(fd,buffer,size,offset);
	if (bytesWriten == -1) {
		cout << strerror(errno) << endl;
	}
	close(fd);
	return bytesWriten;
}

void DiskUtils::eraseBlock(int offset, int blockSize) {
	int zero = 0;
	int fd = open("FILE_SYS", O_WRONLY, 0666);
	for (int i=0; i<blockSize; i++) {
		if (pwrite(fd,&zero,1,offset+i) == -1) {
			//cout << strerror(errno) << endl;
		}
	}
	close(fd);
}
